package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	"hft/Http/Models/response"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
)

type BrokerHelp struct{}

func (*BrokerHelp) GetLouPanList(paginate *request.BrokerHelpPage, claims tools.BaseClaims) (data *utils.Page, err error) {

	var account *admin.Account

	var louPans []*admin.LouPan

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	err = global.OC_DB.Model(&account).Scopes(dao.BrokerHelpDao.GetLouPanList(paginate, global.OC_DB)).Association("LouPan").Find(&louPans)

	if err != nil {
		return nil, errors.New("未知错误500")
	}
	count := global.OC_DB.Model(&account).Scopes(dao.BrokerHelpDao.Search(paginate, global.OC_DB)).Association("LouPan").Count()

	paginate.Total = count
	paginate.Data = louPans

	return &paginate.Page, nil
}

func (*BrokerHelp) GetLouPanInfo(id int, claims tools.BaseClaims) (data *response.LouPanInfo, err error) {

	var account *admin.Account

	var louPan []*admin.LouPan

	var rooms []*admin.Room

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	global.OC_DB.Model(&account).Scopes(dao.BrokerHelpDao.PreloadInfo(global.OC_DB)).Association("LouPan").Find(&louPan, id)

	if len(louPan) == 0 {
		return nil, errors.New("无权限获取该信息")
	}

	var info = louPan[0]

	var ids []int

	for _, v := range info.RoomType {
		ids = append(ids, int(v.ID))
	}

	global.OC_DB.Where("lou_pan_id = ? AND room_id IN ?", id, ids).Preload("RoomSwiper").Preload("SellStatus").Find(&rooms)

	var res = &response.LouPanInfo{
		LouPan: *louPan[0],
		Rooms:  rooms,
	}

	return res, nil
}

var BrokerHelpServices = new(BrokerHelp)
